package com.sduept.nwld.dataserver.controller.daily;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.entity.core.RecordAttachment;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.nwld.dataserver.manager.protection.SpecialReportManager;

@Named
@ViewScoped
public class SpecialReportMapController extends AbstractController {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4585213205131305242L;
	@Autowired
	private SpecialReportManager ma;
	@Autowired
	private CommonDocumentProperties pros;
	private StreamedContent file;
	private boolean fileExist = false;

	public void fileDownloadView() {
		file = null;
		Map<String, String> request = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String fileId = request.get("fileId");
		fileDownloadView(fileId);
	}
	public void fileDownloadView(String id) {
		RecordAttachment recordAttachment = ma.findFileById(id);
		InputStream stream = null;
		try {
			stream = new FileInputStream(pros.getDocumentPath() + recordAttachment.getName());
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} finally{
			if(stream == null){
				fileExist = false;
			}else{
				fileExist = true;
			}
		}
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
				.getExternalContext().getRequest();
		try {
			String agent = request.getHeader("User-Agent").toLowerCase();
			if (agent != null
					&& (agent.indexOf("msie") != -1 || (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1))
					|| agent.indexOf("edge") != -1) {
				file = new DefaultStreamedContent(stream, "application/octet-stream", URLEncoder.encode(
						recordAttachment.getDescription(), "UTF-8"));
			} else {
				file = new DefaultStreamedContent(stream, "application/octet-stream", new String(
						recordAttachment.getDescription().getBytes("UTF-8"), "ISO8859-1"));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}
	public boolean isFileExist() {
		return fileExist;
	}
	public void setFileExist(boolean fileExist) {
		this.fileExist = fileExist;
	}
	
}
